package cn.hl.hm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hl.hm.controller.CheckVehicleController;
import net.sf.json.JSONObject;

public class CheckVehicle {
	private static final Logger logger = LoggerFactory.getLogger(CheckVehicleController.class);
	private final static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
	private static final String targetURL = "https://ssl.logink.org/authapi/rest/auth/apply?userid=13833&password=dingdangdao2017&resource=120380A218FC003EE053C0A87F0C003E";
	static JSONObject xml = postJson(targetURL);
	static String token = xml.get("token").toString();

	public static void main(String[] args) {
 	System.out.println(checkJieRuReturnCarInfo("皖AC3698"));
//		System.out.println(checkRuWang("黑BR6664"));

	}

	/**
	 * 入网异常判定
	 * 
	 * @param vehicleNumber 错误的车牌号，会进catch
	 * @return resultCode 0：未入网，1：入网 searchCode 02
	 */
	public static int checkRuWang(String vehicleNumber) {
		logger.info("车辆入网验证..");
		Object data = 0;
		try {
			String jieruURLOK = "http://credit.logink.org/gateway/restfulQry!qry.htm?method=CheckPersonVehicleEnterpriseInformation&actionType=QueryVehicleCredit&result_format=1&sec={%22userid%22:%2213833%22,%22token%22:%22"+token+"%22}&charset=utf-8&biz_content={%22VehicleNumber%22:%22"+URLEncoder.encode(vehicleNumber, "utf8")+"%22,%22SearchTypeCode%22:%2221%22}";
//			System.out.println(postJson(jieruURLOK));
			JSONObject json = postJson(jieruURLOK);
			JSONObject jsonObject = JSONObject.fromObject(json.toString());
			data = jsonObject.get("biz_result");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("vehicleInformationResult");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("resultCode");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			data=  0;
		}
		return Integer.parseInt((data.toString()));
	}

	/**
	 * 道路许可证过期异常判定
	 * 
	 * @param vehicleNumber
	 * @return 0：正常，1：过期 searchCode 21
	 */
	public static int checkJieRu(String vehicleNumber) {
		int result = 0; // 正常
//		System.out.println("token:" + token);
		try {
			String jieruURL = "http://credit.logink.org/gateway/restfulQry!qry.htm?method=QueryVehicleCredit&result_format=1&sec={%22userid%22:%2213833%22,%22token%22:%22"+token+"%22}&charset=utf-8&biz_version=&biz_content={%22VehicleNumber%22:%22"+URLEncoder.encode(vehicleNumber, "utf8")+"%22,%22LicensePlateTypeCode%22:%22%E9%BB%84%E8%89%B2%22,%20%22SearchTypeCode%22:%2202%22}";
//			System.out.println(URLEncoder.encode(vehicleNumber, "utf8"));
			JSONObject json = postJson(jieruURL);
			JSONObject jsonObject = JSONObject.fromObject(json.toString());
			Object data = jsonObject.get("biz_result");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("Body");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("RoadTransportCertificateInformation");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("PeriodEndDate");// 获取过期日期
			// 比较日期 ，判断是否过期
			if (shortSdf.parse(data.toString()).before(new Date())) {
//				System.out.println("过期");
				result = 1;
				// todo 修改接入异常字段信息
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			result = 1;
			
		}
		return result;
	}
	
	
	/**
	 * 道路许可证过期异常判定
	 * 
	 * @param vehicleNumber
	 * @return 0：正常，1：过期 searchCode 21
	 */
	public static Date checkJieRuReturnDate(String vehicleNumber) {
		int result = 0; // 正常
//		System.out.println("token:" + token);
		try {
			String jieruURL = "http://credit.logink.org/gateway/restfulQry!qry.htm?method=QueryVehicleCredit&result_format=1&sec={%22userid%22:%2213833%22,%22token%22:%22"+token+"%22}&charset=utf-8&biz_version=&biz_content={%22VehicleNumber%22:%22"+URLEncoder.encode(vehicleNumber, "utf8")+"%22,%22LicensePlateTypeCode%22:%22%E9%BB%84%E8%89%B2%22,%20%22SearchTypeCode%22:%2202%22}";
//			System.out.println(URLEncoder.encode(vehicleNumber, "utf8"));
			JSONObject json = postJson(jieruURL);
			JSONObject jsonObject = JSONObject.fromObject(json.toString());
			Object data = jsonObject.get("biz_result");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("Body");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("RoadTransportCertificateInformation");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("PeriodEndDate");// 获取过期日期
			// 比较日期 ，判断是否过期
			return shortSdf.parse(data.toString()) ;
//			 

		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
			
		}
		 
	}
	/**
	 * 道路许可证过期异常判定
	 * 
	 * @param vehicleNumber
	 * @return 0：正常，1：过期 searchCode 21
	 */
	public static JSONObject checkJieRuReturnCarInfo(String vehicleNumber) {
		int result = 0; // 正常
//		System.out.println("token:" + token);
		try {
			String jieruURL = "http://credit.logink.org/gateway/restfulQry!qry.htm?method=QueryVehicleCredit&result_format=1&sec={%22userid%22:%2213833%22,%22token%22:%22"+token+"%22}&charset=utf-8&biz_version=&biz_content={%22VehicleNumber%22:%22"+URLEncoder.encode(vehicleNumber, "utf8")+"%22,%22LicensePlateTypeCode%22:%22%E9%BB%84%E8%89%B2%22,%20%22SearchTypeCode%22:%2202%22}";
//			System.out.println(URLEncoder.encode(vehicleNumber, "utf8"));
			JSONObject json = postJson(jieruURL);
			JSONObject jsonObject = JSONObject.fromObject(json.toString());
			Object data = jsonObject.get("biz_result");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("Body");
			jsonObject = JSONObject.fromObject(data.toString());
			data = jsonObject.get("RoadTransportCertificateInformation");
			return JSONObject.fromObject(data.toString());
//			data = jsonObject.get("PeriodEndDate");// 获取过期日期
//			// 比较日期 ，判断是否过期
//			return shortSdf.parse(data.toString()) ;
//			 

		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
			
		}
		 
	}

	/**
	 * 向指定URL发送post方法的请求，请求内容为json格式的字符串
	 * 
	 * @param urlString
	 * @param jsonObject
	 * @return JSONObject 直接返回json对象
	 */
	public static JSONObject postJson(String urlString) {
		JSONObject returnJson = null;
		try {
			// 创建连接
			URL url = new URL(urlString);
			try {
				SslUtils.ignoreSsl();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 
			connection.connect();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); 
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				sb.append(lines);
			}
			returnJson = JSONObject.fromObject(sb.toString());
			reader.close();
			// 断开连接
			connection.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnJson;
	}
}